import { frontRoutes } from '@/router/frontRoute';
import { RouteRecordRaw } from 'vue-router';

/**
 * 路由树节点接口
 */
export interface RouteTreeNode {
	name: string;
	title: string;
	children?: RouteTreeNode[];
}

/**
 * 将路由数据转换为简单的树型结构
 * @param routes 路由数组
 * @returns 树型结构数组
 */
function convertRoutesToTree(routes: RouteRecordRaw[]): RouteTreeNode[] {
	const tree: RouteTreeNode[] = [];

	routes.forEach((route) => {
		// 跳过隐藏的路由
		if (route.meta?.isHide) {
			return;
		}

		const node: RouteTreeNode = {
			name: route.name as string || route.path,
			title: route.meta?.title || route.name as string || route.path
		};

		// 处理子路由
		if (route.children && route.children.length > 0) {
			const children = convertRoutesToTree(route.children);
			if (children.length > 0) {
				node.children = children;
			}
		}

		tree.push(node);
	});

	return tree;
}

/**
 * 获取前端路由树型结构
 * @returns 路由树型结构数组
 */
export function getRouteTree(): RouteTreeNode[] {
	const routes = frontRoutes.dynamicRoutes;
	if (!routes || routes.length === 0) {
		return [];
	}

	// 找到根路由（通常是 path: '/' 的路由）
	const rootRoute = routes.find((route) => route.path === '/');
	if (!rootRoute || !rootRoute.children) {
		return [];
	}

	// 转换根路由的 children 为树型结构
	return convertRoutesToTree(rootRoute.children);
}

/**
 * 前端路由树型结构（直接暴露，供其他 Vue 组件直接使用）
 */
export const routeTree: RouteTreeNode[] = (() => {
	const routes = frontRoutes.dynamicRoutes;
	if (!routes || routes.length === 0) {
		return [];
	}

	// 找到根路由（通常是 path: '/' 的路由）
	const rootRoute = routes.find((route) => route.path === '/');
	if (!rootRoute || !rootRoute.children) {
		return [];
	}

	// 转换根路由的 children 为树型结构
	return convertRoutesToTree(rootRoute.children);
})();

/**
 * 根据路由名称查找路由树节点
 * @param routeTree 路由树
 * @param routeName 路由名称
 * @returns 找到的路由节点，未找到返回 null
 */
export function findRouteNode(routeTree: RouteTreeNode[], routeName: string): RouteTreeNode | null {
	for (const node of routeTree) {
		if (node.name === routeName) {
			return node;
		}
		if (node.children) {
			const found = findRouteNode(node.children, routeName);
			if (found) {
				return found;
			}
		}
	}
	return null;
}

/**
 * 获取所有路由名称（扁平化）
 * @param routeTree 路由树
 * @returns 路由名称数组
 */
export function getAllRouteNames(routeTree: RouteTreeNode[]): string[] {
	const names: string[] = [];
	
	function traverse(nodes: RouteTreeNode[]) {
		nodes.forEach((node) => {
			names.push(node.name);
			if (node.children) {
				traverse(node.children);
			}
		});
	}
	
	traverse(routeTree);
	return names;
}

